package org.yasukusury.crawler.variation;

import org.apache.http.client.utils.DateUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.yasukusury.crawler.dao.Copy;
import org.yasukusury.crawler.dao.List;
import org.yasukusury.crawler.helper.Result;
import org.yasukusury.crawler.helper.Utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Y
 * Date: 2017-11-11
 * Time: 21:57
 */
public class AmazonCNCrawler extends AbstractBatches{
    private static final String[] dateFormat = new String[]{"于 yyyy年MM月dd日"};
    private static final String userAgent = "Mozilla/5.0 (jsoup)";
    private static final int timeout = 5 * 1000;
    private String[] param = new String[]{"ie", "UTF8", "reviewerType", "all_reviews", "pageNumber", "1"};
    private String url;
    private String title;
    private String reviewUrl;

    public AmazonCNCrawler(String asin) {
        this.asin = asin;
        reviewUrlPrase(asin);
    }

    void start() throws InterruptedException {
        list = new ConcurrentLinkedDeque<>();

        try {
            fillList();
        } catch (IOException e) {
            e.printStackTrace();
        }
        pageTraverse();
    }

    void fillList() throws IOException {
        Document productDoc = Jsoup.connect(url).userAgent(userAgent).timeout(timeout).get();
        Element reviewSummary = productDoc.getElementById("reviewSummary");
        Element star = reviewSummary.child(1).child(0);
        Element count = reviewSummary.child(0).child(0).child(0).child(0).child(1).child(0).child(0);
        String starText = Utils.getPlainText(star);
        String countText = Utils.getPlainText(count).replaceAll(",", "");

        Integer reviewCount = Integer.parseInt(countText);
        Double avgStar = Double.parseDouble(starText.substring(0, 3));

        Element productTitle = productDoc.getElementById("productTitle");
        title = Utils.getPlainText(productTitle);

    }

    void pageTraverse() throws InterruptedException {
//        int count = result.getList().getTotalCount();
//        Integer pagenum = 1;
//        while (count > 0) {
//            param[5] = pagenum.toString();
//            fillCopies(count > 0 ? count : count + 10);
//            count -= 10;
//            pagenum++;
//        }
    }

    @Override
    void fillCopies() throws InterruptedException {

    }

    @Override
    String dateparse(String text) {
        return null;
    }

    void fillCopies(int count) throws IOException {
        reviewUrlPrase(title);
        System.out.println(reviewUrl);
        Document reviewDoc = Jsoup.connect(reviewUrl).userAgent(userAgent).timeout(timeout).data(param).get();
        Elements reviewList = reviewDoc.getElementById("cm_cr-review_list").children();

        Copy curCopy;
        for (int i = 0; i < 10 && count > 0; i++) {
            curCopy = new Copy();
            Element index = reviewList.get(i).child(0);
            Element reviewStar = index.child(0).child(0).child(0).child(0);
            Element reviewTitle = index.child(0).child(2);
            Element reviewer = index.child(1).child(0).child(2);


            Element createDate = null;
            int member = 1;
            while (index.child(1).childNodeSize() > member){
                if (index.child(1).child(member).attributes().dataset().containsValue("review-date"))
                    createDate = index.child(1).child(member);
                member += 1;
            }

            member = 0;
            Element format = null;
            Element purchased = null;
            while (index.child(2).childNodeSize() > member){
                if (index.child(2).child(member).attributes().dataset().containsValue("format-strip"))
                    format = index.child(2).child(member);
                if (index.child(2).child(member).child(0).childNodeSize()>0)
                    if (index.child(2).child(member).child(0).child(0).childNodeSize()>0)
                        if (index.child(2).child(member).child(0).child(0).attributes().dataset().containsValue("avp-badge"))
                            purchased = index.child(2).child(member);

                member += 1;
            }

            Element content = index.child(3).child(0);
            curCopy.setStar(Integer.parseInt(Utils.getPlainText(reviewStar).substring(0, 1)));
            curCopy.setTitle(Utils.getPlainText(reviewTitle));
            curCopy.setReviewer(Utils.getPlainText(reviewer));
            curCopy.setCreateDate(DateUtils.parseDate(Utils.getPlainText(createDate), dateFormat));
            curCopy.setPurchased(Utils.getPlainText(purchased));
            curCopy.setContent(Utils.getPlainText(content));
            list.add(curCopy);
            count--;
        }
    }

    private void urlPrase(String asin) {
        StringBuilder sb = new StringBuilder("https://www.amazon.cn/");
        sb.append("dp/");
        sb.append(asin);
        url = sb.toString();
    }

    private void reviewUrlPrase(String title) throws IllegalArgumentException {
        if ("".equals(title) || title == null)
            throw new IllegalArgumentException("解析商品标题失败");
        StringBuilder sb = new StringBuilder("https://www.amazon.cn/");
        sb.append(getUTF8XMLString(title));
        sb.append("/product-reviews/");
        sb.append(asin);
        reviewUrl = sb.toString();
    }

    private String getUTF8XMLString(String xml) {
        // A StringBuffer Object
        String xmString = "";
        String xmlUTF8 = "";
        try {
            xmString = new String(xml.getBytes("UTF-8"));
            xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");
//            System.out.println(xmlUTF8) ;
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // return to String Formed
        return xmlUTF8;
    }

}
